<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'mf:fj:mfCarplanFjH:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="40%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />


    <BasicModal
      v-bind="$attrs"
      :showFooter="true"
      :okAuth="'mf:fj:mfCarplanFjH:edit'"
      @register="registerModal2"
      @ok="handleSubmit2"
      width="80%"
    >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> 批量添加详情</span> 
    </template>
      <BasicTable @register="registerTable3" @row-click="handleTable3RowClick"></BasicTable>
    </BasicModal>

  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWmsWeighbridgeFjForm2">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { CarplanDh, mfCarplanDhCForm, mfCarplanDhCSave } from '/@/api/wms/weighbridge/dh';
  import { CarplanFj, mfCarplanFjForm, mfCarplanFjSave,mfCarplanFjHListForm,mfCarplanFjHListSave } from '/@/api/wms/weighbridge/fj';
  import { BasicModal, useModalInner,useModal } from '/@/components/Modal';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('sys.fj');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<CarplanFj>({} as CarplanFj);
  const carType = ref<any>('');
  const hid = ref<string>('');
  const type = ref<string>('');
  const mfCarplanFjC = ref<any>({});

    

  const getTitle = computed(() => ({
    icon: meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增废旧物资装车计划详情') : t('编辑废旧物资装车计划详情'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('合同号'),
      field: 'htNo',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('物资名称'),
      field: 'invName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('客户名称'),
      field: 'cusName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('规格型号'),
      field: 'invStd',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('单位'),
      field: 'invUnit',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('承运目的地'),
      field: 'cyAddress',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('承运单价'),
      field: 'cyPrice',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('净重'),
      field: 'jzWeight',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      ifShow: false,

    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 200,
      },
    },
  ];


  const tableColumns3: BasicColumn[] = [
    {
      title: t('车次号'),
      dataIndex: 'parent.djNo',
      width: 150,
    },
    {
      title: t('车牌号'),
      dataIndex: 'parent.carNo',
      width: 150,
    },
    {
      title: t('合同号'),
      dataIndex: 'htNo',
      width: 120,
      editRow: true,
      editComponent: 'Input',
      editRule: true,
    },
    {
      title: t('物资名称'),
      dataIndex: 'invName',
      width: 120,
      editRow: true,
      editComponent: 'Input',
      editRule: true,
    },
    {
      title: t('客户名称'),
      dataIndex: 'cusName',
      width: 120,
      editRow: true,
      editComponent: 'Input',
      editRule: true,
    },
    {
      title: t('规格型号'),
      dataIndex: 'invStd',
      width: 120,
      editRow: true,
      editComponent: 'Input',
      editRule: false,
    },
    {
      title: t('单位'),
      dataIndex: 'invUnit',
      width: 120,
      editRow: true,
      editComponent: 'Input',
      editRule: false,
    },
    {
      title: t('承运目的地'),
      dataIndex: 'cyAddress',
      width: 120,
      editRow: true,
      editComponent: 'Input',
      editRule: false,
    },
    {
      title: t('承运单价'),
      dataIndex: 'cyPrice',
      width: 120,
      editRow: true,
      editComponent: 'InputNumber',
      editRule: false,
    },
    {
      title: t('净重'),
      dataIndex: 'jzWeight',
      width: 120,
      editRow: true,
      editComponent: 'Input',
      editRule: false,
      ifShow: false,
    },
    {
      title: t('备注'),
      dataIndex: 'remarks',
      width: 120,
      editRow: true,
      editComponent: 'Input',
      editRule: false,
    },
  ];

  const [registerModal2, { openModal:openModal2, closeModal:closeModal2,setModalProps:setModalProps2 }] = useModal();
  const [registerTable3, xqtable3] = useTable({
    columns: tableColumns3, //配置表格内容数组对象
    showIndexColumn: false,
    canResize: true, //表格是否flex布局
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    autoSubmitOnEnter: true,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    console.log(data,'data===')
    hid.value = data?.hid;
    type.value = data.type || '';

    const res = await mfCarplanFjForm(data);
    carType.value = res.carType
    record.value = (res.mfCarplanFjC || {}) as CarplanFj;
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      if(type.value == '批量'){
        data.selIds = record.value.hid;
        console.log(data,'data====');
        const res = await mfCarplanFjHListForm(data);
        mfCarplanFjC.value = res.mfCarplanFjC || {};
        setTimeout(closeDrawer);
        await openModal2(true, {});
        await xqtable3.setTableData([])
        // await xqtable3.setTableData(res.mfCarplanFjC.rdsList)
        res.mfCarplanFjC.rdsList.forEach((item) => {
          xqtable3.insertTableDataRecord({
            editable: true,
            ...item,
            id:'',
          });
        });
      }else{
        const params: any = {
          isNewRecord: record.value.isNewRecord,
          id: record.value.id,
        };
        // data.hid = hid.value;
        data.hid = record.value.hid;
        const res = await mfCarplanFjSave(params, data);
        showMessage(res.message);
        setTimeout(closeDrawer);
        emit('success', data);
      }
      
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  function handleTable3RowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  async function getChildList() {
    let childListValid = true;
    let childList: Recordable[] = [];
    for (const record of xqtable3.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        childListValid = false;
      }
      childList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    
    if (!childListValid) {
      throw { errorFields: [{ name: ['childList'] }] };
    }
    return childList;
  }

  async function handleSubmit2() {
    try {
      const params: any = {
          isNewRecord: record.value.isNewRecord,
      };
      let data = {
        ...mfCarplanFjC.value,
        rdsList:[]
      }
      setModalProps2({ confirmLoading: true });
      data.rdsList = await getChildList();
      const res = await mfCarplanFjHListSave(data);
      showMessage(res.message);
      closeModal2();
      // setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setModalProps2({ confirmLoading: false });
    }
  }
</script>
